<script setup lang='ts' name="object-management-add">
import { useQualificationAddOrUpdate, useQualificationShow } from '@fl/api/anjutong/qualification-ticket'
import type { QualificationSave } from '@fl/api/anjutong/model/qualification-ticket-model'
import type { PlusColumn } from 'plus-pro-components'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { getProjects } from '@fl/api/anjutong'
import { formatTime } from '@fl/utils'
import FlUpload from '@fl/components/fl-upload.vue'
import searchMap from '../components/search-map.vue'

const { go } = useRouter()
const route = useRoute()

const _id = route.query?.id as string
const id = ref(_id ?? '')
const isCopy = route.query.type === 'copy'
const isEdit = route.query.type === 'edit'
console.log('进来了', id.value, isCopy, isEdit)

const formRef = ref()
const projectList = ref<any>([])
const selctProject = ref<any>([])
const updateKey = ref<number>(1)
const isChooseAll = ref(false)
const menuTreeRef = ref()
const projectLength = ref<number>(0)

const initialState = {
    endTime: '',
    startTime: '',
    validTime: [], // 有效期-临时
    qrCodeUrl: '', // 小程序码
    positionLimit: '0', // 是否限制领取位置
    projectId: [], // 选择项目id集合
    qualificationProjectRelevanceList: [], // 所选的项目
    // valueAmount: undefined,
    longitude: undefined,
    latitude: undefined,
    distanceLimit: 1000, // 距离限制
    addressName: '',
    grantQuantity: 2000, // 每日发放数量
}
const state = ref<QualificationSave>(cloneDeep(initialState))

// 项目详情
const { data, isLoading } = useQualificationShow(id)
watchEffect(() => {
    if (data.value) {
        state.value = {
            ...data.value,
            projectId: isCopy ? [] : data.value.qualificationProjectRelevanceList.map(item => ([item.companyId, item.projectId])),
            qualificationProjectRelevanceList: isCopy ? [] : data.value.qualificationProjectRelevanceList,
            validTime: data.value.startTime ? [data.value.startTime, data.value.endTime] : [],
            distanceLimit: data.value?.distanceLimit || 1000,
            grantQuantity: data.value?.grantQuantity || 2000,
        }
        projectList.value.forEach((company) => {
            company.projectVOS.forEach((project) => {
                if (project.companyId) {
                    projectLength.value += 1
                }
            })
        })
        if (data.value.qualificationProjectRelevanceList.length === projectLength.value) {
            isChooseAll.value = true
        }
        else {
            isChooseAll.value = false
        }
        console.log('详情', state.value)
        updateKey.value = +new Date()
    }
})

init()

function init() {
    getProjectList()
}

// 获取项目列表
function getProjectList() {
    getProjects().then((res) => {
        projectList.value = res
        if (projectList.value?.qualificationProjectRelevanceList?.length === projectLength.value) {
            isChooseAll.value = true
        }
        else {
            isChooseAll.value = false
        }
    })
}

// 切换选择位置
function changePositionRadio() {
    console.log('changePositionRadio', 222)
}

function projectChange(vals) {
    state.value.qualificationProjectRelevanceList = []
    const values = vals.flat(Infinity)
    selctProject.value = [...new Set(values)]
    // console.log('projectChange', selctProject.value)
}

// 上传图片后清除提示
function qrCodeUrlChange() {
    formRef.value.formInstance.clearValidate('qrCodeUrl')
}

// 提交表单
const { isPending, mutate } = useQualificationAddOrUpdate()

async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        setProject(projectList.value, selctProject.value)
        const stateObj = toRaw(state.value)
        if (state.value.qualificationProjectRelevanceList.length === 0) {
            ElMessage({
                message: '关联项目不能为空',
                type: 'warning',
            })
            return
        }
        if (state.value.positionLimit === '1' && !state.value.addressName) {
            ElMessage({
                message: '请输入地址，或输入后点击查找并选择地址',
                type: 'warning',
            })
            return
        }
        // 过滤掉仅有父级的数据
        const list = state.value.qualificationProjectRelevanceList.reduce((pre: any, cur: any) => {
            if (cur.projectId) {
                pre.push(cur)
            }
            return pre
        }, [])
        const params = {
            ...stateObj,
            endTime: state.value.validTime[1],
            startTime: state.value.validTime[0],
            id: isEdit ? id.value : undefined,
            latitude: state.value.positionLimit === '0' ? '' : state.value.latitude,
            longitude: state.value.positionLimit === '0' ? '' : state.value.longitude,
            distanceLimit: state.value.positionLimit === '0' ? '' : state.value.distanceLimit,
            addressName: state.value.positionLimit === '0' ? '' : state.value.addressName,
            qualificationProjectRelevanceList: list,
        }
        // console.log('params', params)
        mutate(params, {
            onSuccess: () => {
                formRef.value.formInstance.resetFields()
                ElMessage.success('操作成功')
                goBack()
            },
        })
    }
}

// 递归获取所选项目列表
function setProject(list: any, projects: any, companyId?: string) {
    // console.log('setProject', list, projects)
    list.forEach((item) => {
        if (projects.includes(item.companyId)) {
            state.value.qualificationProjectRelevanceList.push({
                projectId: item.projectId,
                projectName: item.projectName,
                companyId: companyId || item.companyId,
                companyName: item.companyName,
            })
            if (item.projectVOS) {
                setProject(item.projectVOS, projects, item.companyId)
            }
        }
    })
}

function goBack() {
    go(-1)
}

function changeChooseAll(value) {
    console.log('changeChooseAll', value)
    if (value) {
        const result: any = []
        projectList.value.forEach((company) => {
            company.projectVOS.forEach((project) => {
                result.push([company.companyId, project.companyId])
            })
        })
        state.value.projectId = result
        const values = result.flat(Infinity)
        selctProject.value = [...new Set(values)]
        formRef.value?.formInstance.clearValidate('projectId')
    }
    else {
        state.value.projectId = []
    }
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '资格券名称',
        prop: 'ticketName',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            maxlength: 6,
            showWordLimit: true,
        },
        label: '资格券类型描述',
        prop: 'ticketDescription',
    },
    {
        colProps: {
            span: 18,
        },
        fieldProps: {
            maxlength: 50,
            showWordLimit: true,
        },
        label: '资格券描述',
        prop: 'receiveDescription',
    },
    {
        colProps: {
            span: 18,
        },
        label: '选择项目',
        prop: 'projectId',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'datetimerange',
            'value-format': 'YYYY-MM-DD HH:mm:ss',
        },
        label: '有效期',
        prop: 'validTime',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 9,
        },
        fieldProps: { min: 1, precision: 0, max: 999999 },
        label: '每日发放数量',
        prop: 'grantQuantity',
        valueType: 'input-number',
    },
    {
        colProps: {
            span: 18,
        },
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 200,
            showWordLimit: true,
        },
        label: '使用须知',
        prop: 'usageTerm',
        valueType: 'textarea',
    },
    {
        colProps: {
            span: 24,
        },
        label: '领取限制',
        prop: 'positionLimit',
    },
    {
        colProps: {
            span: 6,
        },
        hideInForm: computed(() => state.value.positionLimit === '0'),
        fieldProps: {
            disabled: true,
        },
        label: '经度',
        prop: 'longitude',
    },
    {
        colProps: {
            span: 6,
        },
        hideInForm: computed(() => state.value.positionLimit === '0'),
        fieldProps: {
            disabled: true,
        },
        label: '纬度',
        prop: 'latitude',
    },
    {
        colProps: {
            span: 24,
        },
        label: '上传活动页小程序码',
        prop: 'qrCodeUrl',
    },
]

const rules = {
    ticketName: [
        {
            message: '活动名称',
            required: true,
        },
    ],
    ticketDescription: [
        {
            message: '资格券类型描述',
            required: true,
        },
    ],
    receiveDescription: [
        {
            message: '资格券描述',
            required: true,
        },
    ],
    validTime: [
        {
            message: '有效期',
            required: true,
        },
    ],
    projectId: [
        {
            message: '选择项目',
            required: true,
        },
    ],
    positionLimit: [
        {
            message: '领取限制',
            required: true,
        },
    ],
    longitude: [
        {
            message: '请选择地点',
            required: true,
        },
    ],
    latitude: [
        {
            message: '请选择地点',
            required: true,
        },
    ],
}
</script>

<template>
    <ElCard shadow="never">
        <el-button @click="goBack">
            返回列表
        </el-button>

        <ElSkeleton v-if="isLoading"
                    :rows="5"
        />

        <template v-else>
            <div class="mt-20">
                <h3 class="title">
                    活动基础信息
                </h3>

                <PlusForm ref="formRef"
                          v-model="state"
                          :columns="columns"
                          :label-width="120"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                          label-position="top"
                >
                    <template #plus-field-projectId>
                        <!-- checkStrictly: true, -->
                        <el-checkbox v-model="isChooseAll"
                                     @change="changeChooseAll"
                        >
                            全选
                        </el-checkbox>

                        <el-cascader ref="menuTreeRef"
                                     v-model="state.projectId"
                                     style="width:100%;padding-right:4px;max-height: 210px;"
                                     :props="{
                                         multiple: true,
                                         value: 'companyId',
                                         label: 'companyName',
                                         children: 'projectVOS',
                                     }"
                                     clearable
                                     filterable
                                     :options="projectList"
                                     @change="projectChange"
                        />
                    </template>

                    <template #plus-field-positionLimit>
                        <el-radio-group v-model="state.positionLimit"
                                        style="width:100%;"
                                        @change="changePositionRadio"
                        >
                            <el-radio value="0">
                                不限
                            </el-radio>

                            <el-radio value="1">
                                指定位置
                            </el-radio>
                        </el-radio-group>

                        <div v-if="state.positionLimit === '1'"
                             class="distance"
                        >
                            <span>附近</span>

                            <el-input v-model="state.distanceLimit"
                                      class="input"
                                      oninput="value=value.replace(/[^0-9]/g,'')"
                            />

                            <span>米</span>
                        </div>

                        <!-- v-model:readonly="isReadOnly" -->
                        <searchMap v-if="state.positionLimit === '1'"
                                   v-model:state="state"
                        />
                    </template>

                    <template #plus-field-qrCodeUrl>
                        <div class="flex">
                            <FlUpload :key="String(updateKey)"
                                      v-model="state.qrCodeUrl"
                                      tips="大小5M以内"
                                      @success="qrCodeUrlChange"
                            />
                        </div>
                    </template>
                </plusform>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    保存
                </SubmitBtn>

                <el-button @click="goBack">
                    取消
                </el-button>
            </div>
        </template>
    </ElCard>
</template>

<style lang="less" scoped>
.title {
    font-size: 20px;
    font-weight: 600;
    margin: 20px 0 16px 0;
}
:deep(.w-full) {
    display: flex;
    .el-upload__tip {
        height: 150px;
        line-height: 260px;
        margin-left: 10px;
    }
}
.distance {
    display: flex;
    margin: -36px 0 0 180px;
    .input {
        width: 60px;
        margin: 0 10px;
    }
}
:deep(.el-cascader__tags) {
    max-height: 200px;
    overflow: auto;
}
</style>
